#include "accelerometer.h"
#include "device.h"
#include "display.h"
#include "power.h"
#include "record.h"
#include "rtc.h"
#include "version.h"

uint	curSteps;
uint	timer;
ushort	error;
ushort	flags;
ubyte	clrSteps;
ubyte	lowPower;
ubyte	status;

DEBUG	debug;
SAVE	savRam;

static void booting(void){
	device_init(0);
	device_watchdog(1);
	device_checkPower();
	rtc_wait();
	device_speed(1);
	device_updateVecTable();
	record_init(RTC_GetCounter()+savRam.timeOfs,curSteps);
	accelerometer_init();
	status=device_status();
}
static void clock(void){
	timer=0;
	display_on();
	if(savRam.timeOfs)
		display_clock((RTC_GetCounter()+savRam.timeOfs)/60);
	else display_error();
	while(status==STATUS_CLOCK){
		__WFI();
		ubyte s=device_status();
		if(s==STATUS_TAP && timer>TIME_TAP)
			status=STATUS_PEDOMETER;
		else if(timer>=1999)
			status=s;
	}
}
static void pedometer(void){
	if(lowPower)
		status=STATUS_STANDBY;
	else{
		timer=0;
		display_on();
		meterOn();
		display_dec(curSteps);
		while(status==STATUS_PEDOMETER){
			__WFI();
			ubyte s=device_status();
			if(s==STATUS_TAP && timer>TIME_TAP)
				status=STATUS_CLOCK;
			else if(timer>=1999)
				status=s;
		}
		meterOff();
	}
}
static void powerDown(void){
	accelerometer_deinit();
	display_on();
	timer=0;
	while(timer<4000){
		display_battery(0);
		__WFI();
	}
	//BKP_WriteBackupRegister(BACKUP_TIMEOFSL,timeOfs);
	//BKP_WriteBackupRegister(BACKUP_TIMEOFSH,timeOfs>>16);
	//BKP_WriteBackupRegister(BACKUP_STEPS,curSteps);
	//ushort ex=curSteps>>16;
	//BKP_WriteBackupRegister(BACKUP_EXTRA,ex);
	//PWR_WakeUpPinCmd(ENABLE);
	PWR_EnterSTANDBYMode();
}
static void silent(ubyte stt){
	display_off();
	while(status==stt){
		PWR_EnterSTOPMode(PWR_Regulator_LowPower,PWR_STOPEntry_WFE);
		SystemInit();
		RCC_HCLKConfig(RCC_SYSCLK_Div4);
		ubyte s=device_status();
		status=s==STATUS_TAP?STATUS_PEDOMETER:s;
	}
}

//------------------------------------------------------------------------------

void main(void){
	while(1){
		switch(status){
		case STATUS_BOOTING:
			booting();
			break;
		case STATUS_CHARGING:
			charging();
			break;
		case STATUS_CLOCK:
			clock();
			break;
		case STATUS_PEDOMETER:
			pedometer();
			break;
		case STATUS_POWERDOWN:
			powerDown();
			break;
		case STATUS_SILENT:
		case STATUS_STANDBY:
			silent(status);
			break;
		default:
			status=device_status();
		}
	}
}